from SpiderTianyancha import SpiderTianyancha
import tkinter
import json
import tkinter.messagebox as tkMessagebox

if __name__ == "__main__":

    bnt_type = ''

    window = tkinter.Tk()

    def get_data(key, page, cookie, text):
        global bnt_type, history

        if bnt_type == 'begin':
            tkMessagebox.showinfo('警告', '程序已在运行中，请勿重复点击!')
            return False

        if not key:
            tkMessagebox.showinfo('警告', '未设置搜索关键字！')
            return False
        elif not page:
            tkMessagebox.showinfo('警告', '未设置搜索页码！')
            return False
        elif not cookie:
            tkMessagebox.showinfo('警告', '未设置cookie！')
            return False
        
        st = SpiderTianyancha(key, cookie, text)

        total_page = st.get_total_page()

        if int(page) > total_page:
            tkMessagebox.showinfo('警告', '搜索页码不应该大于总页数！')
            return False

        bnt_type = 'begin'

        st.update_text_info('此类信息共计：'+str(total_page)+'页')

        current_page = int(page)
        while current_page <= total_page and bnt_type == 'begin':
            try:
                if st.write_info(current_page):
                    st.update_text_info('已爬取第'+str(current_page)+'页')
                    current_page += 1
                else:
                    st.update_text_info('第'+str(current_page)+'页没有写入成功')
                    break
            except Exception as e:
                st.update_text_info(e)
                break

        history = {
            'key': key,
            'page': current_page,
            'cookie': cookie
        }
        
        end_project(bnt_type, st)

    def save_history():
        global history
        with open('data/history.json', 'w', encoding='utf-8') as fp:
            fp.write(json.dumps(history))

    def change_bnt_type(type_set):
        global bnt_type
        
        if type_set == 'end' and bnt_type == 'pause':
            save_history()
            window.destroy()
        elif type_set == 'pause' and bnt_type == 'pause':
            tkMessagebox.showinfo('警告', '当前程序已处于暂停状态，请勿重复点击!')
        elif type_set == 'end' and bnt_type == 'end':
            tkMessagebox.showinfo('警告', '当前程序已处于退出状态，请勿重复点击!')
        else:
            bnt_type = type_set

    def end_project(type_set, st):
        global bnt_type

        if type_set == 'begin':
            st.update_text_info('任务结束！')
            bnt_type = 'pause'
        elif type_set == 'pause':
            st.update_text_info('任务已暂停！')
        elif type_set == 'end':
            st.update_text_info('任务已关闭！')

        if type_set == 'end':
            save_history()
            window.destroy()
        else:
            global page_num_init, keyword_init
            page_num_init.set(history['page'])
            keyword_init.set(history['key'])

    def close_fn():
        if bnt_type:
            tkMessagebox.showinfo('警告', '您已运行过程序，请使用“退出”按钮，关闭程序')
        else:
            window.destroy()

    window.title('天眼查爬虫')
    window.iconbitmap('tianyan.ico')
    # 窗口大小
    window.geometry('540x300+550+500')
    window.protocol("WM_DELETE_WINDOW", close_fn)
    window.resizable(width=False, height=False)

    # 读取历史记录
    with open('data/history.json', 'r', encoding='utf-8') as fp:
        history = json.loads(fp.read())
        if (not 'key' in history) or (not 'page' in history) or not 'cookie' in history:
            history = {
                'key': '',
                'page': '1',
                'cookie': ''
            }
        

    # 组件
    # 第一行
    keyword_label = tkinter.Label(window, text='请输入要查询的关键字', anchor='w', width=17)
    keyword_label.place(x=2, y=2)

    keyword_init = tkinter.StringVar(value=history['key'])
    keyword = tkinter.Entry(window, width=30, bd=1, textvariable=keyword_init)
    keyword.place(x=130, y=3)

    page_label = tkinter.Label(window, text='请输入要开始查询的页数', anchor='w', width=19)
    page_label.place(x=350, y=2)

    page_num_init = tkinter.StringVar(value=history['page'])
    page_num = tkinter.Entry(window, width=6, bd=1, textvariable=page_num_init)
    page_num.place(x=492, y=3)

    # 第二行
    cookie_label =  tkinter.Label(window, text='Cookie', anchor='w')
    cookie_label.place(x=2, y=34, width=46)

    cookie_init = tkinter.StringVar(value=history['cookie'])
    cookie = tkinter.Entry(window, bd=1, textvariable=cookie_init)
    cookie.place(x=50, y=35, width=488)

    # 第三行
    show_info = tkinter.Listbox(window, relief="solid")
    show_info.place(x=2, y=68, width=536, height=190)
    # 添加个滚动条
    yscrollbar = tkinter.Scrollbar(show_info)
    show_info['yscrollcommand'] = yscrollbar.set
    yscrollbar.place(x=515, y=0, height=186)
    yscrollbar.config(command=show_info.yview)

    begin_button = tkinter.Button(window, text='开始', command=lambda:get_data(keyword.get(), page_num.get(), cookie.get(), show_info))
    begin_button.place(x=2, y=260, width=60)

    pause_button = tkinter.Button(window, text='暂停', command=lambda:change_bnt_type('pause'))
    pause_button.place(x=72, y=260, width=60)

    end_button = tkinter.Button(window, text='退出', command=lambda:change_bnt_type('end'))
    end_button.place(x=142, y=260, width=60)

    window.mainloop()